package com.jsh.erp.cloud.service;

import com.jsh.erp.datasource.entities.Function;
import com.jsh.erp.datasource.entities.UserBusiness;
import com.jsh.erp.service.functions.FunctionService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuService {
    @Autowired
    private FunctionService functionService;
    @Resource
    private UserBusinessService userBusinessService;

    public List<Function> getMenus(String userId) throws Exception {
        List<UserBusiness> roleList = userBusinessService.getBasicData(userId, "UserRole");
        Long roleId = getId(roleList.get(0).getValue());
        List<UserBusiness> funList = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions");
        String funcIds = funList.get(0).getValue();
        return functionService.getFunctionListByIds(replaceSquareBrackets(funcIds));
    }

    private Long getId(String value) {
        if(StringUtils.hasText(value)) {
            return Long.valueOf(replaceSquareBrackets(value));
        }
        return null;
    }

    private static List<Long> getIdList(String value) {
        if(StringUtils.hasText(value)) {
            String[] ids = replaceSquareBrackets(value).split(",");
            return Arrays.stream(ids).mapToLong(Long::new).boxed().collect(Collectors.toList());
        }
        return null;
    }

    private static String replaceSquareBrackets(String value) {
        String result = StringUtils.replace(value, "[", "").replace("]", ",");
        return result.substring(0, result.length() - 1);
    }

}
